﻿#region Header
// Copyright 2007-2011, Jerónimo Milea
// 
// This file is part of NetJsWire.
// 
//     NetJsWire is free software: you can redistribute it and/or modify
//     it under the terms of the GNU General Public License as published by
//     the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
// 
//     NetJsWire is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU General Public License for more details.
// 
//     You should have received a copy of the GNU General Public License
//     along with NetJsWire.  If not, see <http://www.gnu.org/licenses/>.
#endregion

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

namespace NetJsWire.JsonRpcHandler.Handlers
{
    internal class ImageRequestProcessor
    {
        private readonly HttpContext _context;

        public ImageRequestProcessor( HttpContext context )
        {
            _context = context;
            //if (context.Session["WebApplication"] != null)
            WebApplication.SetInstanceContext( context );
            //WebApps.Getobject(context.Session.SessionID);
            //WebApplication.Instance = (WebApplication)WebApps.Getobject(_context.Session["WebApplication"].ToString());

            if ( WebApplication.Instance.IsNull )
            {
                throw new Exception( "Instance shouldn't be null :S" );
            }
        }

        public void Process()
        {
            //_context.Response.Clear();
            _context.Response.Cache.SetExpires( DateTime.Now.AddDays( 60 ) );
            _context.Response.Cache.SetCacheability( HttpCacheability.Public );
            _context.Response.Cache.SetValidUntilExpires( true );
            _context.Response.Cache.SetVaryByCustom( "_id" );

            var memStream = new MemoryStream();
            var id = _context.Request.QueryString[ "_id" ];
            var obj = WebApplication.Instance.Objects[ id ];
            var original = GetBitmapReference( obj );
            if ( original != null )
            {
                var bmp = new Bitmap( original );
                _context.Response.ContentType = "image/gif";

                if ( original.RawFormat.Guid == ImageFormat.Jpeg.Guid )
                    _context.Response.ContentType = "image/jpeg";
                if ( original.RawFormat.Guid == ImageFormat.Png.Guid )
                    _context.Response.ContentType = "image/png";
                var format = original.RawFormat;

                if ( format.Guid == ImageFormat.MemoryBmp.Guid )
                {
                    _context.Response.ContentType = "image/png";
                    format = ImageFormat.Png;
                }
                bmp.Save( memStream, format );
                memStream.WriteTo( _context.Response.OutputStream );
                memStream.Flush();
                bmp.Dispose();
                memStream.Close();
                memStream.Dispose();
            }
            else
            {
                _context.Response.ContentType = "image/gif";
                var bmp = new Bitmap( 1, 1 );
                bmp.Save( memStream, ImageFormat.Gif );
                memStream.WriteTo( _context.Response.OutputStream );
                memStream.Flush();
                bmp.Dispose();
                memStream.Close();
                memStream.Dispose();
            }
            _context.Response.End();
        }

        private static Image GetBitmapReference( object obj )
        {
            var pi = obj.GetType().GetProperty( "Image" );

            if ( pi != null )
                return pi.GetValue( obj, null ) as Image;

            pi = obj.GetType().GetProperty( "Picture" );

            if ( pi != null )
                return pi.GetValue( obj, null ) as Image;

            return null;
        }
    }
}